package com.hetang.maijiayun.adaptertools.utils;

import java.io.ByteArrayInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

public class Md5 {
	public Md5() {
	}
	
	//亚马逊特殊的MD5规则
	public static String getMd5_2(String fileStr){
		try{
	        DigestInputStream dis = new DigestInputStream(new ByteArrayInputStream(fileStr.getBytes()), MessageDigest.getInstance( "MD5" ));
	        byte[] buffer = new byte[8192];
	        while( dis.read( buffer ) > 0 );
	        String md5Content = new String( org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest()) );           
	        return md5Content;
		}catch(Exception e){
		}
		return null;
	}

	public static String getMd5(String... inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		if(inStr != null && inStr.length != 0){
			String str = "";
			
			for(String s : inStr){
				if(StringUtils.areNotEmpty(s))
					str += s;
			}
			
			char[] charArray = str.toCharArray();
			byte[] byteArray = new byte[charArray.length];

			for (int i = 0; i < charArray.length; i++)
				byteArray[i] = (byte) charArray[i];

			byte[] md5Bytes = md5.digest(byteArray);

			StringBuffer hexValue = new StringBuffer();

			int val;
			for (int i = 0; i < md5Bytes.length; i++) {
				val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}

			return hexValue.toString();
		}
		return "";
	}
	
	/**
	 * 根据给定的字节返回MD5加密的内容
	 * @Author MC	
	 * @Date 2012-7-23下午02:34:10
	 * @param bytes
	 * @return String
	 * @throws
	 */
	public static String getMd5(byte[] charArray){
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		if(charArray!=null&&charArray.length!=0){
			byte[] byteArray = new byte[charArray.length];
			for (int i = 0; i < charArray.length; i++)
				byteArray[i] = (byte) charArray[i];
			byte[] md5Bytes = md5.digest(byteArray);
			StringBuffer hexValue = new StringBuffer();
			int val;
			for (int i = 0; i < md5Bytes.length; i++) {
				val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}
			return hexValue.toString();
		}
		return "";
	}
	public static void main(String[] args){
		System.err.println(Md5.getMd5("wedsdfsdf"));
		System.err.println(Md5.getMd5("wedsdfsdf",""));
	}
	
}